Create a dictionary from a string tracking the count of the letters¶
Create a dictionary from a string.
Note:
Track the count of the letters from the string.
Sample string:
‘pyHowTo’
Expected output:
{‘3’: 1, ‘s’: 1, ‘r’: 2, ‘u’: 1, ‘w’: 1, ‘c’: 1, ‘e’: 2, ‘o’: 1}
def create_dict_from_string_simple(S):
new_dict = {}
for x in S:
new_dict[x] = S.count(x)
return new_dict
def create_dict_from_string(S):
from collections import defaultdict, Counter
new_dict = {}
for letter in S:
new_dict[letter] = new_dict.get(letter, 0) + 1
return new_dict
Test:
S = 'abra cadabra'
print(create_dict_from_string_simple(S)) # {'a': 5, 'b': 2, 'r': 2, ' ': 1, 'c': 1, 'd': 1}
print(create_dict_from_string(S)) # {'a': 5, 'b': 2, 'r': 2, ' ': 1, 'c': 1, 'd': 1}